var mysql = require("mysql");

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {    
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
　　　　　　　　　　　　var reg= new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

function checkCallback(callback) {
	return callback || function() {}
}

var pool = mysql.createPool({
	hotst: '192.168.31.136',
	user: 'root',
	password: 'ww123',
	database: 'smallgame',
	port: 3306
});


function query(sql,callback){  
    pool.getConnection(function(err,conn){  
        if(err){  
            callback(err,null,null);  
        }else{  
            conn.query(sql,function(qerr,vals,fields){  
                //释放连接  
                conn.release();  
                //事件驱动回调  
                callback(qerr,vals,fields);  
            });  
        }  
    });  
};

var dNameIndex = 10000
function randNickName() {
	return '游客' + dNameIndex++;
}


exports.is_user_exist = function(service_id, callback) {
	var callback = checkCallback(callback);
	if (service_id == null) {
		callback(false);
		return
	}

	var sql = 'SELECT * FROM base_user WHERE service_id = ' + service_id;
	console.log("sql=", sql)
	query(sql, function(err, rows, fields) {
		if (err) {
			throw err;
		}
		if (rows.length == 0) {
			callback(false);
			return;
		}
		callback(true);
	})
}

//接受到一个新的service_id，也就是一个新的用户
exports.insert_service_id = function(service_id, callback) {
	var callback = checkCallback(callback);
	if (service_id == null) {
		callback(false);
		return 
	}
	//var sql = 'INSERT INTO base_user(service_id) VALUES("' + service_id + '")';
	var sql = 'INSERT INTO base_user(service_id, name, coins) VALUES ("{0}", "{1}", {2})';

	tt = sql.format(service_id, randNickName(), 1000);
	console.log(tt)
	query(tt, function(err, rows, fields) {
		if (err) {
			throw err;
		}
		callback(true);
	});
}
